<template>
  <div v-loading="loading" class="app-container" style="height: 100%;">
    <el-row style="display: flex;height: 100%;">
      <el-col :span="6" class="log-list-left">
        <!-- 左侧树结构 -->
        <el-card class="left-tree" style="height: 100%;">
          <el-tree
            ref="tree"
            style="height: 100%;"
            highlight-current
            class="filter-tree customer-tree-box"
            :data="departTree"
            :props="{ label: 'name' }"
            node-key="id"
            :default-expanded-keys="defaultList"
            @node-click="selectNode"
          />
        </el-card>
      </el-col>
      <el-col :span="18" class="log-list-right">
        <!-- 右侧结构 -->
        <el-card class="container-card">
          <div
            slot="header"
            style="height: 60px;"
          >
            <span>作业范围</span>
            <div v-if="currentNode.type!==1" style="float: right; margin-right: 40px">
              <el-tooltip
                effect="dark"
                content="点击编辑释放绘制电子围栏功能"
                placement="top"
              >
                <el-button
                  v-show="showEdit"
                  class="save-area-btn"
                  @click="editData"
                >编辑</el-button>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="点击保存上传绘制好的电子围栏"
                placement="top"
              >
                <el-button
                  v-show="showSave"
                  class="save-area-btn"
                  @click="createData"
                >提交</el-button>
              </el-tooltip>
              <el-button
                v-show="showSave"
                class="cancel-area-btn"
                @click="cancelData"
              >取消</el-button>
            </div>
          </div>
          <div class="searchBox">
            <div class="keyword">
              <label>地区关键词：</label>
              <el-input
                v-model="keyword"
                placeholder="请输入地区关键词"
              />
            </div>
          </div>
          <baidu-map
            class="map"
            :center="center"
            :zoom="zoom"
            :scroll-wheel-zoom="true"
            :map-click="false"
            @mousemove="syncPolyline"
            @click="paintPolyline"
            @rightclick="newPolyline"
            @ready="ready"
          >
            <bm-polygon
              v-for="(path, index) in polyline.paths"
              :key="index"
              :path="path"
              fill-color="rgb(177, 224, 248)"
              :fill-opacity="0.5"
              :stroke-opacity="0.1"
              :editing="polyline.editing"
              @lineupdate="updatePolygonPath"
            />
            <bm-local-search
              :keyword="keyword"
              :auto-viewport="true"
              :panel="false"
            />
            <bm-control
              v-show="showSave"
              style="background: #fff; width: 100%"
            >
              <el-button
                type="primary"
                class="new-btn"
                @click="toggle('polyline')"
              >{{ polyline.editing ? '完成绘制' : '开始绘制' }}</el-button>
              <el-button
                v-show="polyline.editing !== false"
                style="
                  color: #818693;
                  border: 1px solid #d8dde3;
                  padding: 10px 20px;
                  margin-left: 12px;
                "
                class="delet"
                @click="clearMap()"
              >删除围栏</el-button>
              <P
                style="
                 font-size: 12px;
                  color: rgb(32, 177, 245);
                  width: 100%;
                  background: rgb(177, 224, 248);
                  width: 100%;
                  height: 30px;
                  line-height: 30px;
                  text-align: left;
                  padding-left: 10px;
                "
              >！点击或拖动鼠标绘制作业范围，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。每个机构仅可支持绘制一个作业范围</P>
            </bm-control>
          </baidu-map>

        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getDepartTree, scopeBusiness, addMap, delMap } from '@/api/base'
import { transListToTreeData } from '@/utils'
export default {
  data() {
    return {
      keyword: '',
      loading: false,
      departTree: [],
      currentNode: { type: 1 },
      defaultList: [],
      showEdit: true,
      showSave: false,
      isFirstEdit: true, // 默认存在作业范围
      isOperation: false, // 已有作业范围不可以开启划线功能
      // 地图数据
      center: {
        lng: 116.404,
        lat: 39.915
      },
      zoom: 11,
      polygonPath: [
      ],
      mapDate: {},
      polyline: {
        editing: false,
        paths: []
      } // 作业范围,绘制的多边形
    }
  },

  methods: {
    async getDepartTree() {
      this.departTree = transListToTreeData(
        JSON.parse(await getDepartTree()),
        '0'
      )
      // 选择第一个节点
      this.currentNode = this.selectFirstNode(this.departTree)
      this.defaultList = this.getFirstNodeId(this.departTree[0])
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.currentNode.id)
      })
      await this.scopeBusiness()
    },
    // 地图初始化
    async ready({ BMap, map }) {
      this.map = map
      this.BMap = BMap
      await this.getDepartTree()
    },
    async scopeBusiness() {
      const res = await scopeBusiness(this.currentNode.id)
      this.mapDate = res
      let pointArr = []
      let noAgencyArange = []
      if (res.polygon && res.polygon.length > 0) {
        if (Array.isArray(res.polygon)) {
          pointArr = res.polygon.map((item) => {
            return { lat: item.latitude, lng: item.longitude }
          })
        }
        this.isHaveAgencyArange = true
      } else {
        this.isHaveAgencyArange = false
        if (res.latitude) {
          noAgencyArange = [{ lat: res.latitude, lng: res.longitude }]
        } else {
          noAgencyArange = [{ lat: '39.915', lng: '116.4045' }]
        }
      }
      const viewPointInfo = this.map && this.map.getViewport(this.isHaveAgencyArange ? pointArr : noAgencyArange)
      this.$set(this.center, 'lng', viewPointInfo.center.lng)
      this.$set(this.center, 'lat', viewPointInfo.center.lat)
      this.zoom = this.isHaveAgencyArange ? viewPointInfo.zoom : 11

      this.isFirstEdit = Boolean(res.polygon && res.polygon.length > 0)
      this.agencyId = this.currentNode.id
      this.$set(this.polyline, 'paths', !pointArr ? [] : [pointArr])
      this.$set(this.polyline, 'editing', false)
    },
    selectFirstNode(arr) {
      let node = null
      if (arr[0].children && arr[0].children.length) {
        node = this.selectFirstNode(arr[0].children)
      } else {
        node = arr[0]
      }
      return node
    },
    getFirstNodeId(node) {
      const ids = [node.id]
      if (node.children && node.children.length > 0) {
        const firstChild = node.children[0]
        const childIds = this.getFirstNodeId(firstChild)
        ids.push(...childIds)
      }
      return ids
    },
    // 查询详情
    async queryDetail() {
      this.loading = true
      this.mapDate = []
      await this.scopeBusiness(this.currentNode.id)
      this.loading = false
    },
    selectNode(data) {
      this.currentNode = data
      this.queryDetail(this.currentNode.id)
    },
    editData() {
      this.showEdit = false
      this.showSave = true
    },
    async createData() {
      this.isOperation = false
      this.polyline.editing = false
      if (this.polyline.paths.length === 0) {
        return this.$message.error('请绘制作业机构范围')
      }
      // 用于解决绘画电子围栏时，取消默认选中点的绘画开启新的绘画时，无法提交的问题
      const arr = []
      this.polyline.paths.forEach((item) => {
        arr.push(item.length)
      })
      const max = Math.max(...arr)
      const indexOfMax = arr.indexOf(max)
      // point坐标点
      const point = (
        !this.isFirstEdit ? this.polyline.paths[indexOfMax] : this.polygonPath
      ).map((item) => {
        return { latitude: item.lat, longitude: item.lng }
      })
      point.push(point[0]) // 手动在数组末尾加上第一个坐标点
      const data = {
        polygon: point,
        type: 1,
        bid: this.currentNode.id
      }
      // 发送请求，调用接口，保存数据
      await addMap(data)
        .then((res) => {
          if (res === null) {
            this.showSave = false
            this.showEdit = true
            this.$emit('newDataes', this.newDataes)
            this.$message.success('电子围栏保存成功')
            this.$set(this.polyline, 'editing', false)
          } else {
            this.$message.error(res.msg || '电子围栏保存失败')
          }
        })
        .catch(() => {
          this.$message.error('电子围栏保存失败')
        })
    },
    cancelData() {
      this.showEdit = true
      this.showSave = false
      this.polyline.editing = false
    },
    updatePolygonPath(e) {
      this.polygonPath = e.target.getPath()
    },
    async clearMap() {
      this.isOperation = false
      this.polyline.editing = false
      this.showSave = true
      this.showEdit = false
      if (!this.isFirstEdit) {
        this.$set(this.polyline, 'paths', [])
      } else {
        // 清除绘制电子围栏
        const res = await delMap(this.currentNode.id)
        if (res === null) {
          this.$message.success('删除机构作业范围成功')
          this.polyline.paths = []
        } else {
          this.$message.error(res.msg || '删除机构作业范围成功')
        }
      }
    },
    // 开启多边形绘制
    toggle(name) {
      this[name].editing = !this[name].editing
      // console.log(this.polyline.editing)
    },
    // 鼠标移动时
    syncPolyline(e) {
      if (!this.polyline.editing || !this.isOperation) {
        return
      }
      const paths = this.polyline.paths
      if (!paths.length) {
        return
      }
      const path = paths[paths.length - 1]
      if (!path.length) {
        return
      }
      if (path.length === 1) {
        path.push(e.point)
      }
      this.$set(path, path.length - 1, e.point)
    },
    // 鼠标右键多边形绘制完成
    newPolyline(e) {
      if (!this.polyline.editing) {
        return
      }
      const paths = this.polyline.paths
      if (!paths.length) {
        paths.push([])
      }
      const path = paths[paths.length - 1]
      path.pop()
      if (path.length) {
        paths.push([])
      }
    },
    paintPolyline(e) {
      if (!this.polyline.editing || this.isFirstEdit) {
        return
      }
      this.isOperation = true
      const { paths } = this.polyline
      !paths.length && paths.push([])
      paths[paths.length - 1].push(e.point)
    }
  }
}
</script>

<style lang="scss" scoped>
.searchBox{
  display: flex;

  label{
    color: #20232a;
    font-weight: 400;
    font-size: 14px;
  }
  ::v-deep .el-input{
    width: 230px;
  }
  .keyword{
    margin-right: 30px;
  }
}
.container-card {
  margin-left: 10px;
}
.container-card:not(:first-child) {
  margin-top: 20px;
}
.left-tree {
  padding: 10px;
}
::v-deep .el-tree-node__content {
  height: 40px;
}
.rote:before {
  width: 6px;
  height: 6px;
  background: #1dc779;
  border-radius: 50%;
  content: "";
  display: inline-block;
  margin-right: 6px;
}
.custom-icon.is-leaf .el-icon-caret-right {
  display: none !important;
}
::v-deep .customer-tree-box {
  .el-tree-node {
    margin: 2px 0 !important;
    .is-focusable {
      position: relative;
      &::before {
        content: '';
        display: inline-block;
        position: absolute;
        left: 6px;
        // width: 1px;
        border-left: #e5e7ec solid 1px;
        height: calc(100% + 3px);
        // 将此类名的最后一项样式设置为none
        &:last-child {
          border-left: none !important;
        }
      }
      margin: 2px 0 !important;
      .el-tree-node {
        .el-tree-node__children {
          margin: 2px 0 !important;
          .el-tree-node {
            .el-tree-node__content {
              .el-tree-node__expand-icon {
                display: none;
              }
              .el-tree-node__label {
                margin-left: 0px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 131px;
              }
            }
          }
        }
      }
    }
  }
  .el-tree-node {
    .el-tree-node {
      .el-tree-node {
        position: relative;
        &::before {
          content: '';
          display: inline-block;
          position: absolute;
          left: 26px;
          // width: 1px;
          border-left: #e5e7ec solid 1px;
          height: calc(100% + 3px);
        }
        // 将此类名的最后一项样式设置为none
      }
    }
  }
}
.save-area-btn {
  background-color: #e15536;
  color: #ffffff;
  width: 90px;
  border-radius: 5px;
  font-weight: 400;
  border: 1px solid #e15536;
  &:hover {
    background: #ffab98;
    border: 1px solid #ffab98;
  }
}
.cancel-area-btn {
  width: 90px;
  color: #2a2929;
  border: 1px solid #d8dde3;
  border-radius: 5px;
  font-weight: 400;
  &:hover {
    background: #ffeeeb;
    border: 1px solid #f3917c;
    color: #e15536;
  }
}
::v-deep .el-card__header {
    padding: 0 0 0 25px!important;
    border-bottom: 0!important;
    background: #f8faff!important;
    font-size: 16px!important;
    font-weight: 700!important;
    color: #2a2929!important;
    height: 60px;
    line-height: 60px;
}
.map{
  width:100%;
  height:520px;
  padding: 20px 0 0 0;
}
.delet {
  &.el-button:focus {
    background-color: #fff;
  }
}
</style>

